import { ChannelActionType, ChannelListType } from './../reducer/channel';
import {
  AdddChannelApi,
  DelChannelApi,
  GetAllChannelApi,
  GetuserChannelApi,
} from '@/api/channel';
import { AppDispatch } from '@/store';
import {
  SetChannel,
  isHaveToken,
  isHaveChannel,
  GetChannel,
} from '@/utils/storage';

/** 获取所有频道Action */
export const GetAllChannelAction = () => {
  return async (dispatch: AppDispatch) => {
    let { data } = await GetAllChannelApi();
    dispatch({ type: 'channel/SaveAllChannel', payload: data.channels });
  };
};

/** 获取用户频道Action */
export const GetuserChannelAction = () => {
  return async (dispatch: AppDispatch) => {
    if (isHaveToken()) {
      let { data } = await GetuserChannelApi();
      SetChannel(data.channels);
      dispatch({ type: 'channel/SaveuserChannel', payload: data.channels });
    } else {
      if (!isHaveChannel()) {
        let { data } = await GetAllChannelApi();
        SetChannel(data.channels.slice(0, 10));
      }
      dispatch({ type: 'channel/SaveuserChannel', payload: GetChannel() });
    }
  };
};

/** 删除用户指定频道Action */
export const DelChannelAction = (id: number) => {
  return async (dispatch: AppDispatch) => {
    if (isHaveToken()) await DelChannelApi(id);
    SetChannel(GetChannel().filter((item) => item.id !== id));
    dispatch({ type: 'channel/DelAddChannel', payload: id });
  };
};

/** 添加指定频道Action */
export const AddChannelAction = (channels: ChannelListType) => {
  return async (dispatch: AppDispatch) => {
    if (isHaveToken()) await AdddChannelApi(channels);
    SetChannel([...GetChannel(), channels]);
    dispatch({ type: 'channel/UpdateAddChannel', payload: channels });
  };
};

/** 设置Channel_id Action */
export const SetChannel_idAction = (channel_id: string): ChannelActionType => {
  return { type: 'articles/SaveChannel_id', payload: channel_id };
};
